package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.demo.common.Result;

import com.example.demo.entity.*;
import com.example.demo.mapper.AwardMapper;
import com.example.demo.mapper.CommentMapper;
import com.example.demo.mapper.MenuMapper;

import com.example.demo.mapper.UserMapper;
import com.example.demo.security.util.JwtUtils;
import com.example.demo.service.*;
import com.github.pagehelper.PageInfo;
import io.jsonwebtoken.lang.Objects;
import io.swagger.annotations.*;
import io.swagger.models.auth.In;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;


@Api(tags="用户接口")
@RestController
@RequestMapping("/user")
//@CrossOrigin(origins="*")
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private AwardService awardService;
    @Resource
    private UserAddressService userAddressService;
    @Resource
    private PrizeService prizeService;

    @Resource
    private UserMapper userMapper;


//        @PostMapping("login")
//        public Result wxLogin(User user) {
//            User res = userService.wxLogin(user);
//            if (res != null)
//                return Result.success(res);
//            else
//                return Result.error("401", "登录失败");
//        }

    @ApiOperation(value = "小程序登录", notes = "用户在小程序中进行登录操作")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "登录成功"),
            @ApiResponse(code = 401, message = "登录失败")
    })
    @PutMapping ("login")
    public Result login(@RequestBody User user){
        User res = userService.wxLogin(user);
        Map<String,String> payload=new HashMap<>();
        payload.put("id",res.getOpenId());
        String token= JwtUtils.createToken(payload);
        Result result=new Result();
        result.setToken(token);
        result.setData(res);
        result.setCode("200");
        result.setMsg("登录成功");
        return result;
    }


        //@PreAuthorize("hasAuthority('sys:address:add')")
        @ApiOperation(value = "新增地址", notes = "用户新增一个新地址")
        @ApiResponses(value = {
                @ApiResponse(code = 200, message = "填写成功"),
                @ApiResponse(code = 401, message = "填写失败")
        })
        @PostMapping("addAddress")
        public Result addAddress (@RequestBody UserAddress userAddress){
            int res = userAddressService.addAddress(userAddress);
            if (res == 1) {
                return Result.success("填写成功");
            } else {
                return Result.error("401", "填写失败");
            }
        }
        //@PreAuthorize("hasAuthority('sys:address:del')")
        @ApiOperation(value = "删除地址", notes = "用户删除指定地址")
        @ApiImplicitParams({
                @ApiImplicitParam(name = "addressId", value = "地址ID", required = true, dataType = "int", paramType = "query"),
                @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "query")
        })
        @ApiResponses(value = {
                @ApiResponse(code = 200, message = "删除成功"),
                @ApiResponse(code = 401, message = "删除失败")
        })
        @PostMapping("deleteAddress")
        public Result delAddress (Integer addressId, String openId){
            int res = userAddressService.deleteAddress(addressId, openId);
            if (res == 1) {
                return Result.success("删除成功");
            } else {
                return Result.error("401", "删除失败");
            }
        }

        //@PreAuthorize("hasAuthority('sys:address:edit')")
        @ApiOperation(value = "修改地址", notes = "用户修改一个新地址")
        @ApiResponses(value = {
                @ApiResponse(code = 200, message = "新增地址成功"),
                @ApiResponse(code = 401, message = "新增地址失败")
        })
        @PutMapping("/editAddress")
        public Result editAddress (@RequestBody UserAddress userAddress){
            int res = userAddressService.editAddress(userAddress);
            if (res == 1) {
                return Result.success("编辑成功");
            } else {
                return Result.error("401", "编辑失败");
            }
        }
        //@PreAuthorize("hasAuthority('sys:address:get')")
        @ApiOperation(value = "获取某个地址", notes = "通过id获取某个地址的详细信息")
        @ApiImplicitParams({
                @ApiImplicitParam(name = "addressId", value = "地址ID", required = true, dataType = "int", paramType = "query"),
                @ApiImplicitParam(name = "openId", value = "用户ID", required = true, dataType = "int", paramType = "query")
        })
        @ApiResponses(value = {
                @ApiResponse(code = 200, message = "获取地址成功"),
                @ApiResponse(code = 401, message = "获取地址失败")
        })
        @PostMapping("/getAddressById")
        public Result getAddressById(Integer addressId, String openId){
            UserAddress res = userAddressService.getAddressById(addressId,openId);
            if(res != null){
                return Result.success(res);
            }else {
                return Result.error("401","获取地址信息失败");
            }
        }

        //@PreAuthorize("hasAuthority('sys:address:get')")
        @ApiOperation(value = "获取地址列表", notes = "用户获取地址列表")
        @ApiImplicitParam(name = "openId", value = "用户ID", required = true, dataType = "int", paramType = "query")
        @ApiResponses(value = {
                @ApiResponse(code = 200, message = "获取地址列表成功"),
                @ApiResponse(code = 401, message = "获取地址列表失败")
        })
        @PostMapping("getAddressList")
        public Result getAddressList (String openId){
            List<UserAddress> res = userAddressService.getAddressList(openId);
            return Result.success(res);
        }


        @ApiOperation(value = "添加奖品", notes = "向指定用户添加奖品")
        @ApiImplicitParams({
                @ApiImplicitParam(name = "openId", value = "用户ID", required = true, dataType = "int", paramType = "query"),
                @ApiImplicitParam(name = "goodId", value = "奖品ID", required = true, dataType = "int", paramType = "query")
        })
        @ApiResponses(value = {
                @ApiResponse(code = 200, message = "添加奖品成功"),
                @ApiResponse(code = 401, message = "添加奖品失败")
        })
        @PostMapping("addUserAward")
        public Result addUserAward (String openId, Integer goodId, Integer activityId, Integer userAddressId){
            int res = awardService.addUserAward(openId, goodId, activityId, userAddressId);
            if (res == 1) {
                return Result.success("添加奖品成功");
            } else {
                return Result.error("401", "添加奖品失败");
            }
        }



        @ApiOperation(value = "抽奖", notes = "参与抽奖活动并获取奖品")
        @ApiImplicitParams({
                @ApiImplicitParam(name = "openId", value = "用户ID", required = true, dataType = "int", paramType = "query"),
                @ApiImplicitParam(name = "activityId", value = "活动ID", required = true, dataType = "int", paramType = "query")
        })
        @ApiResponses(value = {
                @ApiResponse(code = 200, message = "抽奖成功"),
                @ApiResponse(code = 401, message = "抽奖失败")
        })
        @PostMapping("lotteryDraw")
        public Result lotteryDraw (Integer activityId, String openId){
            UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("open_id",openId);
            User user = userMapper.selectOne(updateWrapper);
            if(user.getLotteryNum() > 0){
                Integer goodId = prizeService.lotteryDraw(activityId);
                if (goodId != 0) {
                    int temp = user.getLotteryNum() - 1;
                    user.setLotteryNum(temp);
                    userMapper.update(user,updateWrapper);
                    return Result.success(goodId);
                } else {
                    return Result.error("401", "抽奖失败");
                }

            }
            return Result.error("401","抽奖次数不足");
        }


        //@PreAuthorize("hasAuthority('sys:prize:get')")
        @ApiOperation(value = "获取奖品列表", notes = "获取指定用户的奖品列表")
        @ApiImplicitParams({
                @ApiImplicitParam(name = "openId", value = "用户ID", required = true, dataType = "int", paramType = "query"),
                @ApiImplicitParam(name = "name", value = "奖品名称",dataType = "String", paramType = "query"),
                @ApiImplicitParam(name = "shipStatus", value = "发货状态",dataType = "String", paramType = "query")
        })
        @ApiResponses(value = {
                @ApiResponse(code = 200, message = "获取奖品列表成功"),
                @ApiResponse(code = 401, message = "获取奖品列表失败")
        })
        @GetMapping("getAwardList")
        public List<Goods> getAwardList (String openId,String  name,String shipStatus){
            List<Goods> awardList = awardService.getUserAwardList(openId);
            Predicate<Goods> predicate = goods -> goods.getGoodName().contains(name)
                    &&goods.getShipStatus().contains(shipStatus);

            List<Goods> result = awardList.stream()
                    .filter(predicate)
                    .collect(Collectors.toList());

            return result;
        }


        //@PreAuthorize("hasAuthority('sys:user:get')")
        @ApiOperation(value = "获取用户信息", notes = "根据用户ID获取用户信息")
        @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "query")
        @ApiResponses(value = {
                @ApiResponse(code = 200, message = "获取用户信息成功"),
                @ApiResponse(code = 500, message = "未能获取用户信息")
        })
        @GetMapping("/getInfoById")
        public Result getInfoById (String openId){
            User res = userService.selectUserById(openId);
            if (res != null) {
                return Result.success(res);
            } else {
                return Result.error("500", "未能获取用户信息");
            }
        }

        @ApiOperation(value = "获取用户数量", notes = "获取系统中的用户数量")
        @ApiResponses(value = {
                @ApiResponse(code = 200, message = "获取用户数量成功"),
                @ApiResponse(code = 500, message = "未能获取用户数量")
        })
        @GetMapping("/getUserCunt")
        public Result getUserCunt () {
            return Result.success(userService.getUserCunt());
        }


        @ApiOperation(value = "获取我参与的活动", notes = "获取用户参与的活动")
        @ApiResponses(value = {
                @ApiResponse(code = 200, message = "获取用户参与的活动"),
                @ApiResponse(code = 500, message = "未能获取用户参与的活动")
        })
        @ApiImplicitParam(name = "openId", value = "用户ID", required = true, dataType = "int", paramType = "query")
        @GetMapping("/getUserActivity")
        public List<Activity> getUserActivity(String openId, String name){
            List<Activity> activityList = userService.getUserActivity(openId);

            Predicate<Activity> predicate = activity -> activity.getActivityName().contains(name);

            List<Activity> result = activityList.stream()
                    .filter(predicate)
                    .collect(Collectors.toList());

            return result;
        }


        @ApiOperation(value = "获取奖品的详细信息", notes = "获取奖品的详细信息")
        @ApiResponses(value = {
                @ApiResponse(code = 200, message = "成功获取奖品的详细信息"),
                @ApiResponse(code = 500, message = "获取奖品的详细信息失败")
        })
        @GetMapping("/getAwardMessage")
        public Result getAwardMessage(String orderId){
            AwardMessage awardMessage = userService.getAwardMessage(orderId);
            return Result.success(awardMessage);
        }

        @Resource
        private CommentService commentService;

        @Resource
        private AwardMapper awardMapper;
        @ApiOperation(value = "用户评价", notes = "用户评价")
        @ApiResponses(value = {
                @ApiResponse(code = 200, message = "评价成功"),
                @ApiResponse(code = 500, message = "评价失败")
        })

        @PutMapping("/userComment")
        public Result userComment(String orderId, String content, @RequestBody Map<String,String> obj, String date, Integer score) throws ParseException {
            UserAward userAward = awardMapper.selectById(orderId);
            int result = commentService.userComment(userAward, content, obj.get("image"), date ,score);
            if(result == 1){
                UpdateWrapper<UserAward> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("order_id", orderId).set("ship_status", 3);
                awardMapper.update(null, updateWrapper);
                return Result.success("用户评价成功");
            }else {
                return Result.error("500","用户评价失败");
            }
        }
        @Resource
        private CommentMapper commentMapper;

        @ApiOperation(value = "用户回复", notes = "用户回复")
        @ApiResponses(value = {
                @ApiResponse(code = 200, message = "回复成功"),
                @ApiResponse(code = 500, message = "回复失败")
        })

        @PutMapping("/userReply")
        public Result userReply(Integer commentId, String reply, @RequestBody Map<String,String> obj, String date, String openId) throws ParseException {
            Comment comment = commentMapper.selectById(commentId);
            int result = commentService.userReply(comment, reply, obj.get("image"), date, openId);
            if(result == 1){
                return Result.success("用户回复成功");
            }else {
                return Result.error("500","用户回复失败");
            }
        }
        @ApiOperation(value = "用户删除评论", notes = "用户删除评论")
        @ApiResponses(value = {
                @ApiResponse(code = 200, message = "删除评论成功"),
                @ApiResponse(code = 500, message = "删除评论失败")
        })
        @DeleteMapping("/deleteComment")
        public Result deleteComment(Integer commentId){
            int result = commentService.deleteComment(commentId);
            if(result == 1){
                return Result.success("用户删除评价成功");
            }else {
                return Result.error("500","用户删除评论失败");
            }
        }

        @ApiOperation(value = "获取订单评价", notes = "获取订单评价")
        @ApiResponses(value = {
                @ApiResponse(code = 200, message = "获取订单评价成功"),
                @ApiResponse(code = 500, message = "获取订单评价失败")
        })
        @GetMapping("/getOrderComment")
        public Result getOrderComment(String orderId){
            Comment comment = commentService.getOrderComment(orderId);
            if(comment != null){
                return Result.success(comment);
            }else {
                return Result.error("500","获取订单评价失败");
            }
        }

        @ApiOperation(value = "确认收货", notes = "确认收货")
        @ApiResponses(value = {
                @ApiResponse(code = 200, message = "确认收货成功"),
                @ApiResponse(code = 500, message = "确认收货失败")
        })
        @PutMapping ("/confirmRecipt")
        public Result confirmRecipt(String orderId){
            int res=userService.confirmRecipt(orderId);
            if(res==1){
                return Result.success("确认收货成功");
            }else{
                return Result.error("500","确认收货失败");
            }
        }



}


